<?php
/**
 * 定时统计每天扫码
 * @author guoxiaoyong
 */
namespace console\controllers;

use yii\console\Controller;
use bc\ar\MActiveRecord;

/**
 * Keyword Controller
 */
class KeywordController extends Controller
{
	public function actionIndex()
	{
		set_time_limit(0);
		$model = new \bc\model\qrcode\ScanModel();
		
		$dao = new MActiveRecord();
		$sql = 'select * from wxch_keywords where `status` = 1';
		
		$result = $dao->getDb()->createCommand($sql)->queryAll();
		
		$last_day_time = strtotime('-1 day', strtotime(date('Y-m-d')));
		
		$current_time = strtotime(date('Y-m-d'));
		
		if($result)
		{
			foreach ($result as $key=>$item)
			{
				$rowSql = 'select * from bc_keyword_statistics where keyword_id = ' . $item['id'] . ' AND create_time = ' . $current_time;
				$row = $dao->getDb()->createCommand($rowSql)->queryOne();
				if(!$row)
				{
					$create_time = $current_time;
					$keyword_id = $item['id'];
					
					//新加当前日期的
					$preSql = $rowSql = 'select * from bc_keyword_statistics where keyword_id = ' . $item['id'] . ' AND create_time = ' . $last_day_time;
					$preRow = $dao->getDb()->createCommand($preSql)->queryOne();
					
					if($preRow)
					{
						$total = $item['count'] - $preRow['total_count'];
						$total = $total < 0 ? 0 : $total;
					}
					else 
					{
						$total = $item['count'] ;
					}
					
					$insertSql = "insert bc_keyword_statistics (keyword_id, total, total_count, create_time) values ({$keyword_id}, {$total}, {$item['count']}, {$create_time})";
					$dao->getDb()->createCommand($insertSql)->execute();					
					
				}
				
			}
		}
		echo 'done';
		
	}
}  

